import CardStore from '..';
import ModeExcel, { CellProps } from '../ModeExcel';
import CubeTrigger from '.';
import _ from 'lodash';
import { action } from 'mobx';
import { message } from 'antd';
import { WeaLocaleProvider } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;

export interface FormulaProps {
    cellrange: string[];
    destcell: string;
    destfield: string;
    formulatxt: string;
    srcformulatxt: String;
}

const EXCEL_SUM = (...args) => {
    let result = 0;
    _.each(args, (v) => {
        if (_.isNumber(v) && !_.isNaN(v)) {
            result = rewrite_add(result,v)
            // result += v;
        }
    })
    return result;
}

/**
 * JS 浮点数求和 精度不对 (0.1+0.2=0.30000000000004等的问题)
 */
const  rewrite_add = (arg1, arg2) =>{
    let r1 = 0, r2 = 0;
    try {
        r1 = arg1.toString().split(".")[1].length;
    } catch (e) { }
    try {
        r2 = arg2.toString().split(".")[1].length;
    } catch (e) { }
    let m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
}

const EXCEL_SUB = (...args) =>{
    let result = args[0]; //第一位参数不处理符号
    args = args.slice(1,args.length);
    _.each(args, (v) => {
        if (_.isNumber(v) && !_.isNaN(v)) {
            if(v<0){
                result = rewrite_add(result,EXCEL_ABS(v));
                // result += EXCEL_ABS(v);
            }else if(v>=0){
                result = rewrite_add(result,-v);
                // result += -v;
            }
        }
    })
    return result;
}
const EXCEL_AVERAGE = (...args) => {
    if (args.length == 0) {
        return 0;
    } else {
        return EXCEL_SUM(...args) / args.length;
    }
}
const EXCEL_ABS = (v) => {
    return Math.abs(v);
}
const EXCEL_ROUND = (value: number, qfws: number) => {
    if (_.isNumber(value) && !_.isNaN(value)) {
        if (_.isInteger(qfws) && !_.isNaN(qfws)) {
            return value.toFixed(qfws);
        } else {
            message.error(`${'EXCEL_ROUND' + getLabel('383715', "第一个参数必须是整数")}`);
        }
    } else {
        message.error(`${'EXCEL_ROUND' + getLabel('521951','第一个参数必须是数字')}`);
    }
    return 0;
}
const EXCEL_IF = (condition, ifValue, elseValue) => {
    if (condition) {
        return ifValue;
    } else {
        return elseValue;
    }
}
const EXCEL_MAX = (...args) => {
    return Math.max(...args);
}
const EXCEL_MIN = (...args) => {
    return Math.min(...args);
}
export default class Formula {
    card: CardStore;
    trigger: CubeTrigger;
    constructor(card, trigger) {
        this.card = card;
        this.trigger = trigger;
    }
    convertCharToInt = (value) => {
        let rtn = 0;
        let powIndex = 0;
        for (let i = value.length - 1; i >= 0; i--) {
            let tmpInt = value[i].charCodeAt() - 64;
            rtn += Math.pow(26, powIndex) * tmpInt;
            powIndex++;
        }
        return rtn;
    }
    getCellField = (...args): CellProps[] => {
        return args.map((d: string) => {
            let [table, xy] = d.split('\.');
            const rowStr = xy.match(/\d+$/);
            const colStr = xy.match(/^[a-zA-Z]+/);
            const rowid = rowStr && parseInt(rowStr[0]) - 1;
            const colid = colStr && this.convertCharToInt(colStr[0]) - 1;
            let _cell: CellProps = {} as any;
            if (table.toUpperCase() == 'MAIN') { //主表字段
                _.each(this.card.modeExcel.cells, (cell: CellProps) => {
                    if (cell.row == rowid && cell.col == colid) {
                        _cell = cell;
                    }
                })
            } else if (table.toUpperCase().startsWith("TAB_")) {
                const tab: ModeExcel = this.card.modeExcel.getTabs(table.toLowerCase());
                _.each(tab.cells, (cell: CellProps) => {
                    if (cell.row == rowid && cell.col == colid) {
                        _cell = cell;
                    }
                })
            } else {
                const detail: ModeExcel = this.card.modeExcel.getExcel(table.toLowerCase());
                _.each(detail.cells, (cell: CellProps) => {
                    if (cell.row == rowid && cell.col == colid) {
                        _cell = cell;
                    }
                })
            }
            return _cell;
        })

    }
    calculate = (formula: FormulaProps, isMain: boolean, key?: string) => {
        if (EXCEL_SUM || EXCEL_AVERAGE || EXCEL_ABS || EXCEL_ROUND || EXCEL_IF || EXCEL_MAX || EXCEL_MIN || EXCEL_SUB) { }
        let _formulaTxt = this.replaceFormula(formula, isMain, key);
        if (_formulaTxt.startsWith('=')) {
            _formulaTxt = _formulaTxt.slice(1);
        }
        return eval(_formulaTxt);
    }

    replaceFormula = (formula: FormulaProps, isMain: boolean, key?: string) => {
        let formulatxt = formula.formulatxt;
        _.each(formula.cellrange, (cell: string) => {
            let rtArray: string[] = [];
            const [fieldCell] = this.getCellField(cell);
            const path = fieldCell.getPath();

            if (isMain) { //赋值给主表
                const { isdetail, detail } = this.card.getFieldProps(path);
                if (isdetail) {
                    if (this.card.cubeForm.has(detail)) {
                        this.card.cubeForm.$(detail).map(row => {
                            if (row.has(path)) {
                                let value = row.$(path).getValue();
                                if (value) {
									if(this.card.getFieldProps(path).fieldhtmltype=='1'&&this.card.getFieldProps(path).fieldtype=='5'){
										value=this.delcommafy(value);
									}
                                    rtArray.push(value);
                                } else {
                                    rtArray.push('0');
                                }
                            }
                        });
                    }
                } else {
                    if (this.card.cubeForm.has(path)) {
                        let value = this.card.cubeForm.$(path).getValue();
                        if (value) {
							if(this.card.getFieldProps(path).fieldhtmltype=='1'&&this.card.getFieldProps(path).fieldtype=='5'){
								value=this.delcommafy(value);
							}
                            rtArray.push(value);
                        } else {
                            rtArray.push('0');
                        }
                    }
                }
            } else { //赋值给明细表
                const { isdetail, detail } = this.card.getFieldProps(path);
                if (isdetail) {
                    if (this.card.cubeForm.has(detail)) {
                        const detailTable = this.card.cubeForm.$(detail);
                        if (detailTable.has(key)) {
                            const row = detailTable.$(key);
                            if (row.has(path)) {
                                let value = row.$(path).getValue();
                                if (value) {
									if(this.card.getFieldProps(path).fieldhtmltype=='1'&&this.card.getFieldProps(path).fieldtype=='5'){
										value=this.delcommafy(value);
									}
                                    rtArray.push(value);
                                } else {
                                    rtArray.push('0');
                                }
                            }
                        }
                    }
                } else {
                    if (this.card.cubeForm.has(path)) {
                        let value = this.card.cubeForm.$(path).getValue();
                        if (value) {
							if(this.card.getFieldProps(path).fieldhtmltype=='1'&&this.card.getFieldProps(path).fieldtype=='5'){
                                value=this.delcommafy(value);
                            }
                            rtArray.push(value);
                        } else {
                            rtArray.push('0');
                        }
                    }
                }
            }
            var curindex = -1;
            while (formulatxt.indexOf(cell) > curindex) {
                curindex = formulatxt.indexOf(cell);
                var str1 = formulatxt.substring(0, curindex);
                var str2 = formulatxt.substring(curindex + cell.length);
                var reg = /^[0-9]$/;
                var nextchar = str2.substr(0, 1);
                if (reg.test(nextchar)) continue;
                formulatxt = str1 + (rtArray.length == 0 ? '0' : rtArray.join(",")) + str2;
            }
        })
        return formulatxt;
    }


    @action
    execute() {
        setTimeout(() => {
            _.each(this.card.modeExcel.formula, (formula: FormulaProps) => {
                const destfield = `field${formula.destfield}`;
                const { isdetail, detail } = this.card.getFieldProps(destfield);
                if (isdetail) { //赋值给明细表
                    const detailTable = this.card.cubeForm.has(detail) && this.card.cubeForm.$(detail);
                    if (detailTable) {
                        detailTable.map(row => {
                            const value = this.calculate(formula, false, row.key);
                            row.has(destfield) &&!row.$(destfield).value && row.$(destfield).onChange(`${value}`,null, [],true);
                        })
                    }
                } else { //赋值给主表
                    const value = this.calculate(formula, true);
                    this.card.cubeForm.has(destfield) && this.card.cubeForm.$(destfield).onChange(`${value}`,null, [],true);
                }
            });
        }, 10);
    }

    doFormulaBindChange=()=>{
        setTimeout(() => {
            _.each(this.card.modeExcel.formula, (formula: FormulaProps) => {
                const destfield = `field${formula.destfield}`;
                const { isdetail, detail } = this.card.getFieldProps(destfield);
                _.each(formula.cellrange, (cell) => {
                    const [fieldCell] = this.getCellField(cell);
                    const path = fieldCell.getPath();
                    const isdetail1 = this.card.getFieldProps(path)&&this.card.getFieldProps(path).isdetail;
                    this.trigger.addOnChange(path, (index) => {
                        let value = 0;
                        if (isdetail) {
                            value = this.calculate(formula, false, index);
                            this.card.cubeForm.has(detail) && this.card.cubeForm.$(detail).map(row => {
                                // if (index && row.index != index) {   //QC403315(W-4),没有取到row.index导致直接返回
                                //     //return;
                                // }
                                if(isdetail1){
                                    this.card.cubeForm.setValue(`${detail}.${index}.${destfield}`, `${value}`,true);
                                }else{// 子表公式配置的是主表字段的时候
                                    this.card.cubeForm.setValue(`${detail}.${row.key}.${destfield}`, `${value}`,true);
                                }
                               
                                //row.has(destfield) && row.$(destfield).onChange(`${value}`);
                            });
                        } else {
                            value = this.calculate(formula, true);
                            this.card.cubeForm.has(destfield) && this.card.cubeForm.$(destfield).onChange(`${value}`,null, [],true);
                        }
                    });
                })
            });
        }, 10);
    }

	delcommafy(num){ //千分位转换成浮点数
        if( (num+"").trim() == ""){
           return"";
        } 
        num=num.replace(/,/gi,'');    
        return num;      
    }

}
